import React, { useState, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { FireDevice } from '../../../types';

interface FireDeviceProps {
  device: FireDevice;
  isSelected?: boolean;
  onClick?: () => void;
}

const FireDeviceComponent: React.FC<FireDeviceProps> = ({
  device,
  isSelected = false,
  onClick
}) => {
  const groupRef = useRef<THREE.Group>(null);
  const [isHovered, setIsHovered] = useState(false);
  
  // 警报动画参考
  const alertAnimationRef = useRef<number>(0);

  // 根据设备类型获取颜色
  const getDeviceColor = (): string => {
    switch (device.type) {
      case 'Extinguisher':
        return '#E91E63'; // 粉红色
      case 'SmokeDetector':
        return '#FF9800'; // 橙色
      case 'HeatDetector':
        return '#F44336'; // 红色
      case 'Sprinkler':
        return '#2196F3'; // 蓝色
      case 'Alarm':
        return '#9C27B0'; // 紫色
      default:
        return '#607D8B'; // 蓝灰色
    }
  };

  // 根据设备状态获取颜色
  const getStatusColor = (): string => {
    switch (device.status) {
      case 'normal':
        return '#4CAF50';
      case 'warning':
        return '#FFC107';
      case 'activated':
        return '#F44336';
      default:
        return '#2196F3';
    }
  };



  // 处理点击事件
  const handleClick = (event: React.MouseEvent) => {
    event.stopPropagation();
    if (onClick) {
      onClick();
    }
  };

  // 处理鼠标悬停事件
  const handleMouseEnter = () => {
    setIsHovered(true);
  };

  const handleMouseLeave = () => {
    setIsHovered(false);
  };



  // 警报动画
  useFrame(() => {
    alertAnimationRef.current += 0.05;
  });

  // 根据设备类型创建不同的模型
  const renderDeviceModel = () => {
    const color = getDeviceColor();
    
    switch (device.type) {
      case 'Extinguisher':
        // 灭火器模型 - 圆柱体带拉杆
        return (
          <group>
            <mesh position={[0, 0.6, 0]} rotation={[0, 0, Math.PI / 2]}>
              <cylinderGeometry args={[0.15, 0.15, 0.6, 8]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
            </mesh>
            
            {/* 灭火器手柄 */}
            <mesh position={[0.3, 0.6, 0.1]}>
              <boxGeometry args={[0.1, 0.1, 0.2]} />
              <meshStandardMaterial color="#795548" roughness={0.7} metalness={0.5} />
            </mesh>
            
            {/* 灭火器拉杆 */}
            <mesh position={[0.35, 0.65, 0.1]} rotation={[Math.PI / 2, 0, 0]}>
              <cylinderGeometry args={[0.05, 0.05, 0.15, 8]} />
              <meshStandardMaterial color="#795548" roughness={0.7} metalness={0.5} />
            </mesh>
            
            {/* 支架 */}
            <mesh position={[0, 0, 0]} rotation={[Math.PI / 2, 0, 0]}>
              <cylinderGeometry args={[0.05, 0.05, 0.6, 8]} />
              <meshStandardMaterial color="#616161" roughness={0.7} metalness={0.4} />
            </mesh>
          </group>
        );
        
      case 'SmokeDetector':
        // 烟雾探测器模型 - 圆形扁平
        return (
          <group>
            <mesh position={[0, 0, 0]}>
              <cylinderGeometry args={[0.15, 0.15, 0.08, 12]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
            </mesh>
            
            {/* 探测器底面 */}
            <mesh position={[0, -0.04, 0]}>
              <cylinderGeometry args={[0.2, 0.2, 0.02, 12]} />
              <meshStandardMaterial color="#424242" roughness={0.7} metalness={0.4} />
            </mesh>
            
            {/* 中间传感器 */}
            <mesh position={[0, 0.02, 0]}>
              <sphereGeometry args={[0.04]} />
              <meshStandardMaterial 
                color="#FFC107" 
                roughness={0.5} 
                metalness={0.2} 
              />
            </mesh>
          </group>
        );
        
      case 'HeatDetector':
        // 热感探测器模型 - 圆形带散热片
        return (
          <group>
            <mesh position={[0, 0, 0]}>
              <cylinderGeometry args={[0.15, 0.15, 0.1, 12]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
            </mesh>
            
            {/* 探测器底面 */}
            <mesh position={[0, -0.05, 0]}>
              <cylinderGeometry args={[0.2, 0.2, 0.02, 12]} />
              <meshStandardMaterial color="#424242" roughness={0.7} metalness={0.4} />
            </mesh>
            
            {/* 散热片 */}
            <group position={[0, 0.05, 0]}>
              {Array.from({ length: 4 }).map((_, index) => (
                <mesh
                  key={`fin-${index}`}
                  rotation={[0, 0, (index * Math.PI) / 2]}
                >
                  <boxGeometry args={[0.2, 0.02, 0.01]} />
                  <meshStandardMaterial color="#FF9800" roughness={0.7} metalness={0.4} />
                </mesh>
              ))}
            </group>
          </group>
        );
        
      case 'Sprinkler':
        // 喷淋头模型 - 小圆形带喷嘴
        return (
          <group>
            <mesh position={[0, 0, 0]}>
              <cylinderGeometry args={[0.1, 0.1, 0.05, 8]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
            </mesh>
            
            {/* 安装底座 */}
            <mesh position={[0, -0.025, 0]}>
              <cylinderGeometry args={[0.12, 0.12, 0.02, 8]} />
              <meshStandardMaterial color="#424242" roughness={0.7} metalness={0.4} />
            </mesh>
            
            {/* 喷嘴 */}
            <mesh position={[0, 0.05, 0]}>
              <cylinderGeometry args={[0.03, 0.03, 0.03, 6]} />
              <meshStandardMaterial color="#9E9E9E" roughness={0.7} metalness={0.5} />
            </mesh>
            
            {/* 喷水效果（如果触发） */}
            {device.status === 'activated' && (
              <group position={[0, 0.08, 0]}>
                <mesh>
                  <coneGeometry args={[0.15, 0.3, 8]} />
                  <meshStandardMaterial 
                    color="#2196F3" 
                    transparent 
                    opacity={0.6} 
                    roughness={0.2} 
                    metalness={0.1}
                  />
                </mesh>
                {/* 水滴 */}
                {Array.from({ length: 8 }).map((_, index) => (
                  <mesh
                    key={`drop-${index}`}
                    position={[
                      Math.sin((index * Math.PI) / 4) * 0.15,
                      -0.1 - (index * 0.05),
                      Math.cos((index * Math.PI) / 4) * 0.15
                    ]}
                  >
                    <sphereGeometry args={[0.02]} />
                    <meshStandardMaterial 
                      color="#2196F3" 
                      roughness={0.2} 
                      metalness={0.3}
                    />
                  </mesh>
                ))}
              </group>
            )}
          </group>
        );
        
      case 'Alarm':
        // 警报器模型 - 方形带喇叭
        return (
          <group>
            <mesh position={[0, 0.2, 0]}>
              <boxGeometry args={[0.25, 0.25, 0.1]} />
              <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
            </mesh>
            
            {/* 喇叭格栅 */}
            <mesh position={[0, 0.2, 0.05]}>
              <planeGeometry args={[0.2, 0.2]} />
              <meshStandardMaterial color="#424242" roughness={0.7} metalness={0.4} />
            </mesh>
            
            {/* 支架 */}
            <mesh position={[0, -0.05, 0]}>
              <boxGeometry args={[0.05, 0.2, 0.05]} />
              <meshStandardMaterial color="#616161" roughness={0.7} metalness={0.4} />
            </mesh>
            
            {/* 警报灯光效果 */}
            {device.status === 'activated' && (
              <mesh
                position={[0, 0.2, 0]}
                scale={1 + Math.sin(alertAnimationRef.current) * 0.2}
              >
                <sphereGeometry args={[0.3]} />
                <meshStandardMaterial 
                  color="#F44336" 
                  transparent 
                  opacity={0.3} 
                  roughness={0.2} 
                  metalness={0.1}
                />
              </mesh>
            )}
          </group>
        );
        
      default:
        // 默认模型
        return (
          <mesh position={[0, 0.1, 0]}>
            <boxGeometry args={[0.2, 0.2, 0.2]} />
            <meshStandardMaterial color={color} roughness={0.6} metalness={0.3} />
          </mesh>
        );
    }
  };

  return (
    <group
      ref={groupRef}
      position={[device.position.x, device.position.y, device.position.z]}
      onClick={handleClick}
      onPointerEnter={handleMouseEnter}
      onPointerLeave={handleMouseLeave}
    >
      {/* 设备主体 */}
      {renderDeviceModel()}
      
      {/* 状态指示器 */}
      <mesh
        position={device.type === 'Sprinkler' ? [0, 0.12, 0] : [0, 0.1, 0]}
        visible={device.type !== 'Extinguisher'}
      >
        <sphereGeometry args={[0.05]} />
        <meshStandardMaterial
          color={getStatusColor()}
          emissive={getStatusColor()}
          emissiveIntensity={device.status === 'activated' ? 1 : 0.6}
          roughness={0.2}
          metalness={0.3}
        />
      </mesh>
      
      {/* 选中边框 */}
      {isSelected && (
        <lineSegments>
          <edgesGeometry
            args={[
              new THREE.BoxGeometry(0.5, 0.5, 0.5)
            ]}
          />
          <lineBasicMaterial
            color="#2196F3"
            linewidth={3}
          />
        </lineSegments>
      )}
      
      {/* 悬停效果 */}
      {isHovered && (
        <lineSegments>
          <edgesGeometry
            args={[
              new THREE.BoxGeometry(0.45, 0.45, 0.45)
            ]}
          />
          <lineBasicMaterial
            color="#64B5F6"
            linewidth={2}
          />
        </lineSegments>
      )}
    </group>
  );
};

export default React.memo(FireDeviceComponent);